﻿using Dapper;
using ERPEF.Model;
using ERPService;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System.Data;

namespace S4Project.Controllers
{
    [Route("api/[controller]/[action]")]
    [Consumes("application/json")]
    [ApiController]
    public class ChaseReceiptController : ControllerBase
    {
        private readonly MyDbContext myDbContext;
        private readonly pur_Chase_ReceiptService _ChaseService;
        public ChaseReceiptController(MyDbContext myDbContext, pur_Chase_ReceiptService pur_Chase_ReceiptService)
        {
            this.myDbContext = myDbContext;
            this._ChaseService = pur_Chase_ReceiptService;
        }

        //采购入库查询
        [HttpGet]
        public ActionResult<FenYe<pur_Chase_Receipt>> ChaseReceiptFenYe(int currentPage, int pageSize, string where)
        {
            using (var conn = myDbContext.Database.GetDbConnection())
            {
                conn.Open();
                var parameters = new DynamicParameters();
                parameters.Add("pageSize", dbType: DbType.Int32, direction: ParameterDirection.Input, value: pageSize);
                parameters.Add("keyName", dbType: DbType.String, direction: ParameterDirection.Input, value: "pr_id"); // 更改为正确的列名
                parameters.Add("tableName", dbType: DbType.String, direction: ParameterDirection.Input, value: "pur_Chase_Receipt"); // 更改为正确的表名
                parameters.Add("currentPage", dbType: DbType.Int32, direction: ParameterDirection.Input, value: currentPage);
                parameters.Add("where", dbType: DbType.String, direction: ParameterDirection.Input, value: where); // 添加 where 参数
                parameters.Add("row", dbType: DbType.Int32, direction: ParameterDirection.Output); // 修改为和存储过程中一致的参数名
                string sql = "[dbo].[FenYe]";
                var result = conn.Query<pur_Chase_Receipt>(sql, parameters, commandType: CommandType.StoredProcedure);
                int row = parameters.Get<int>("row");
                FenYe<pur_Chase_Receipt> fenye = new FenYe<pur_Chase_Receipt>()
                {
                    ChaseReceipt = result,
                    Rows = row,
                };

                if (fenye.ChaseReceipt.Any())
                {
                    return fenye;
                }
                else
                {
                    return Content("没有查到数据");
                }
            }
        }

        //主-入库添加
        [HttpPost]
        public async Task<IActionResult> ChaseReceiptAdd([FromBody] pur_Chase_Receipt chase_Receipt)
        {
            if (ModelState.IsValid)
            {
                // 查询当前最大编码
                int maxCodeNumber = int.Parse(await GetMaxProductsNumber());

                // 生成新编码
                string newCode = GenerateSaleProducts(maxCodeNumber);

                chase_Receipt.pr_number = newCode;

                int res = await _ChaseService.ReceiptAdd(chase_Receipt);
                if (res > 0)
                {
                    return Ok("添加成功");
                }
                else
                {
                    return BadRequest("添加失败！");
                }
            }
            else
            {
                return BadRequest(ModelState);
            }
        }
        //产品
        private async Task<string> GetMaxProductsNumber()
        {
            // 从数据库中获取最大的仓库编码数字部分
            string maxProductsString = await myDbContext.pur_Purchase_Order
                .Where(w => w.ord_number.StartsWith("CGRK"))
                .Select(w => w.ord_number.Substring(10))
                .OrderByDescending(code => code)
                .FirstOrDefaultAsync<string?>();

            // 如果数据库中没有记录或者记录的编码不符合预期格式，则返回 "0001"
            if (string.IsNullOrEmpty(maxProductsString))
            {
                return "1";
            }
            // 解析最大编码的数字部分
            int maxCodeNumber = int.Parse(maxProductsString);
            Console.WriteLine(maxCodeNumber);

            // 生成新的编码数字部分
            int newCodeNumber = maxCodeNumber + 1;

            // 如果新的编码数字部分超过了99，则重置为01
            if (newCodeNumber > 99)
            {
                newCodeNumber = 1;
            }

            return newCodeNumber.ToString();

        }
        // 生成新的编码
        private string GenerateSaleProducts(int codeNumber)
        {
            // 获取当前日期的字符串表示形式，格式为 "yyyyMMdd"
            string dateString = DateTime.Now.ToString("yyyyMMdd");

            // 将数字转换为两位字符串，并在前面补零
            string codeString = codeNumber.ToString("D2");

            // 返回完整的编码，包括前缀 "CGRK"、日期部分和数字部分
            return "CGRK" + dateString + codeString;
        }

        //主-入库修改
        [HttpPut]
        public async Task<IActionResult> OrderUpdate(pur_Chase_Receipt chase_Receipt)
        {
            if (ModelState.IsValid)
            {
                chase_Receipt.pur_Chase_From = null;
                int res = await _ChaseService.ReceiptUpdate(chase_Receipt);
                if (res > 0)
                {

                    return Ok("修改成功！");

                }
                else
                {
                    return BadRequest("修改失败");
                }
            }
            else
            {
                return BadRequest(ModelState);
            }
        }

        //主-入库删除
        [HttpDelete("{pr_id}")]
        public async Task<string> FromDelete(int pr_id)
        {
            var sal = await myDbContext.pur_Chase_Receipt
                .Include(m => m.pur_Chase_From)
                .SingleOrDefaultAsync(m => m.pr_id == pr_id);
            if (sal == null || sal.IsDeleted == true)
            {
                return "未找到对应的数据";
            }
            var undeletedFroms = sal.pur_Chase_From.Any(f => f.IsDeleted == false);

            if (undeletedFroms)
            {
                return "存在关联数据，删除失败";
            }
            sal.IsDeleted = true;
            await myDbContext.SaveChangesAsync();

            return "删除成功";
        }


        //采购入库修改查询
        [HttpGet]
        public ActionResult<FenYe<pur_Chase_From>> ChaseFromFenYe(int currentPage, int pageSize, string where)
        {
            using (var conn = myDbContext.Database.GetDbConnection())
            {
                conn.Open();
                var parameters = new DynamicParameters();
                parameters.Add("pageSize", dbType: DbType.Int32, direction: ParameterDirection.Input, value: pageSize);
                parameters.Add("keyName", dbType: DbType.String, direction: ParameterDirection.Input, value: "pf_id"); // 更改为正确的列名
                parameters.Add("tableName", dbType: DbType.String, direction: ParameterDirection.Input, value: "pur_Chase_From"); // 更改为正确的表名
                parameters.Add("currentPage", dbType: DbType.Int32, direction: ParameterDirection.Input, value: currentPage);
                parameters.Add("where", dbType: DbType.String, direction: ParameterDirection.Input, value: where); // 添加 where 参数
                parameters.Add("row", dbType: DbType.Int32, direction: ParameterDirection.Output); // 修改为和存储过程中一致的参数名
                string sql = "[dbo].[FenYe]";
                var result = conn.Query<pur_Chase_From>(sql, parameters, commandType: CommandType.StoredProcedure);
                int row = parameters.Get<int>("row");
                FenYe<pur_Chase_From> fenye = new FenYe<pur_Chase_From>()
                {
                    ChaseFrom = result,
                    Rows = row,
                };

                if (fenye.ChaseFrom.Any())
                {
                    return fenye;
                }
                else
                {
                    return Content("没有查到数据");
                }
            }
        }

        //从-添加
        [HttpPost]
        public async Task<IActionResult> FromAdd(pur_Chase_From chase_From)
        {
            if (ModelState.IsValid)
            {
                int res = await _ChaseService.FromAdd(chase_From);
                if (res > 0)
                {
                    return Ok("添加成功！");
                }
                else
                {
                    return BadRequest("添加失败！");
                }
            }
            else
            {
                return BadRequest(ModelState);
            }
        }

        //从-修改
        [HttpPut]
        public async Task<IActionResult> FromUpdate(pur_Chase_From chase_From)
        {
            if (ModelState.IsValid)
            {
                int res = await _ChaseService.FromUpdate(chase_From);
                if (res > 0)
                {
                    return Ok("修改成功！");
                }
                else
                {
                    return BadRequest("修改失败！");
                }
            }
            else
            {
                return BadRequest(ModelState);
            }
        }

        //从-删除
        [HttpDelete("{pf_id}")]
        public async Task<IActionResult> FromPurDelete(int pf_id)
        {
            int res = await _ChaseService.FromDelete(pf_id);
            if (res > 0)
            {
                return Ok("删除成功！");
            }
            else
            {
                return NotFound("删除失败！");
            }
        }



        //采购入库审核
        [HttpPost("{pr_id}")]
        public async Task<IActionResult> AuditSalesOrder(int pr_id)
        {
            // 从数据库中获取销售订单及其关联的订单详情
            var salesOut = await myDbContext.pur_Chase_Receipt
                .Include(so => so.pur_Chase_From) // 确保加载关联的订单详情
                .FirstOrDefaultAsync(so => so.pr_id == pr_id);

            // 如果采购订单不存在或已经被逻辑删除，则返回错误信息
            // 检查从表sal_Orders是否有数据
            if (!salesOut.pur_Chase_From.Any() || salesOut.pur_Chase_From.All(order => order.IsDeleted))
            {
                return BadRequest("从表没有数据，不能进行审核");
            }
            // 检查从表pur_Purchase_From是否有数据
            if (!salesOut.pur_Chase_From.Any())
            {
                return BadRequest("从表没有数据，不能进行审核");
            }
            try
            {
                // 审核销售入库
                salesOut.pr_state = '1'; //订单状态
                salesOut.pr_wareouse = '2'; //入库状态
                salesOut.AuditStatus = true; //审核状态
                salesOut.auditor = "admin"; //审核人
                salesOut.auditTime = DateTime.Now;//审核时间

                // 同时更新关联的销售订单状态
                var salesOrder = await myDbContext.pur_Purchase_Order
                    .FirstOrDefaultAsync(so => so.ord_number == salesOut.pr_number);

                if (salesOrder != null)
                {
                    salesOrder.ord_state = salesOut.pr_state; // 更新采购订单状态
                    salesOrder.ord_warehouse = salesOut.pr_wareouse; // 更新入库状态状态
                }

                if (salesOut.pr_wareouse == '2')
                {
                    foreach (var returnItem in salesOut.pur_Chase_From)
                    {
                        var invStorage = new inv_Storage
                        {
                            ow_id = 0,
                            ow_item_name = returnItem.fro_purname,
                            ow_specification = salesOut.pr_number,
                            ow_item_attributes = "产品",
                            ow_unit = "包",
                            ow_quantity = (int)returnItem.pf_price,
                            ow_warehouse = returnItem.w_Name,
                            ow_operators = salesOut.pr_operators,
                            ow_storage_date = DateTime.Now,
                            ow_type = "采购入库",
                            ow_audit = false,
                            IsDeleted = false,
                            ow_create_by = "Admin",
                            ow_create_time = DateTime.Now,
                            ow_update_by = "Admin",
                            ow_update_time = DateTime.Now,
                        };
                        myDbContext.inv_Storage.Add(invStorage);
                    }
                }

                // 保存更改到数据库
                await myDbContext.SaveChangesAsync();

                return Ok("审核成功，已入库 ");
            }
            catch (DbUpdateException ex)
            {
                return StatusCode(500, "审核失败，数据库更新异常：" + ex.Message);
            }
        }

    }
}
